//
//  toolHelp.m
//  GC_OC
//
//  Created by 叶建辉 on 2022/6/19.
//

#import "toolHelp.h"

@implementation toolHelp

+(void)DownLoadResourcesWithUrl:(NSString *)url fileName:(NSString *)fileName downLoading:(McBack)jhprogress downLoadEnd:(McBack)back{
    NSURL *URL = [NSURL URLWithString:url];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSessionDownloadTask *_downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        if (downloadProgress) {
            
            jhprogress(@(1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount));
            
//            NSLog(@"这个进度为%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        }
        
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径
        
//        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
        NSLog(@"pathpathpath~~>>%@",fileName);
        return [NSURL fileURLWithPath:fileName];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        // filePath就是你下载文件的位置，你可以解压，也可以直接拿来使用
        NSString *imgFilePath = [filePath path];// 将NSURL转成NSString
        //        UIImage *img = [UIImage imageWithContentsOfFile:imgFilePath];
        NSLog(@"imgFilePathimgFilePath~~>%@",imgFilePath);
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:imgFilePath]) {
            back(imgFilePath);
        }else{
            back(@"");
        }
        
        
        
    }];
    [_downloadTask resume];
}

+(void)saveHistoryData:(NSDictionary *)dataDic andID:(NSString *)ablid{
    NSArray *dataArray = [[NSUserDefaults  standardUserDefaults] arrayForKey:@"getcatedetail"];
    if (dataArray == nil) {
        NSMutableArray *tempMutArray = [NSMutableArray array];
        [tempMutArray addObject:@{
            @"id": ablid,
            @"data":[toolHelp convertToJsonData:dataDic]
        }];
        [[NSUserDefaults  standardUserDefaults] setValue:tempMutArray forKey:@"getcatedetail"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        NSMutableArray *tempMutArray = dataArray.mutableCopy;
       NSDictionary *dictData = @{
            @"id": ablid,
            @"data":[toolHelp convertToJsonData:dataDic]
       };
        BOOL isHave = NO;
        for (int i = 0; i < dataArray.count; i++) {
            NSDictionary *tempdict = dataArray[i];
            if ([tempdict[@"id"] isEqualToString:ablid]) {
                [tempMutArray removeObjectAtIndex:i];
                [tempMutArray insertObject:dictData atIndex:0];
                isHave = YES;
                break;
            }
        }
        if (!isHave) {
            [tempMutArray insertObject:dictData atIndex:0];
        }

        [[NSUserDefaults  standardUserDefaults] setValue:tempMutArray.copy forKey:@"getcatedetail"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

+(NSString *)convertToJsonData:(NSDictionary *)dict

{

    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonString;

    if (!jsonData) {

        NSLog(@"%@",error);

    }else{

        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];

    NSRange range = {0,jsonString.length};

    //去掉字符串中的空格

    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

    NSRange range2 = {0,mutStr.length};

    //去掉字符串中的换行符

    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    return mutStr;

}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
//    NSLog(@"jsonString~~~>%@",jsonString);
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+(NSString *)timeFormatted:(int)totalSeconds
{

    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;

    if (hours == 0) {
        return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
    }
    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
}

+(NSString *)getVideoLengthFromTimeLength:(float)timeLength{
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:timeLength];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSInteger unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ;
    NSDateComponents *components = [calendar components:unitFlags fromDate:date];
    NSLog(@"~~components.hour~~>%zd",components.hour);
    if (components.hour == 0) {
        return [NSString stringWithFormat:@"%@:%@:%@",components.hour < 10?[NSString stringWithFormat:@"0%zd",components.hour]:[NSString stringWithFormat:@"%zd",components.hour],components.minute < 10?[NSString stringWithFormat:@"0%zd",components.minute]:[NSString stringWithFormat:@"%zd",components.minute],components.second < 10?[NSString stringWithFormat:@"0%zd",components.second]:[NSString stringWithFormat:@"%zd",components.second]];
    }
    return [NSString stringWithFormat:@"%@:%@",components.minute < 10?[NSString stringWithFormat:@"0%zd",components.minute]:[NSString stringWithFormat:@"%zd",components.minute],components.second < 10?[NSString stringWithFormat:@"0%zd",components.second]:[NSString stringWithFormat:@"%zd",components.second]];
}


+(NSInteger)getToInt:(NSString*)strtemp
{
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData* da = [strtemp dataUsingEncoding:enc];
    return [da length];
}

+(NSArray *)get32String:(NSString *)str andFont:(float)font{
    NSMutableString *mutstr = NSMutableString.string;
    NSMutableString *mutstr1 = NSMutableString.string;
    for (int i = 0; i < str.length; i++) {
        [mutstr appendString:[str substringWithRange:NSMakeRange(i, 1)]];
        if ([mutstr sizeWithFont:[UIFont systemFontOfSize:font] constrainedToSize:CGSizeMake(MAXFLOAT, font)].width>WIDTHDiv*.95) {
            mutstr = [mutstr.copy substringToIndex:[mutstr length] - 1].copy;
            break;
        }
    }
    
    for (NSInteger i = mutstr.length; i < str.length; i++) {
        [mutstr1 appendString:[str substringWithRange:NSMakeRange(i, 1)]];
    }
    
    if (mutstr1.length>0) {
//        NSLog(@"str~~~>>%@mutstr~~>>%@mutstr1-->>%@font~~>%lf",str,mutstr,mutstr1,font);
    }
    
    return @[mutstr.copy,mutstr1.copy];
}

@end
